package com.cug.zfanspring.service;


import com.cug.zfanspring.bean.User;
import com.cug.zfanspring.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
@Transactional
public class UserService {
    @Autowired
    UserMapper userMapper;
    public User loadUserByUsername(String s){
        User user=userMapper.loadUserByUsername(s);
        if (user == null) {
            //避免返回null，这里返回一个不含有任何值的User对象，在后期的密码比对过程中一样会验证失败
            return new User();
        }
        return user;
    }

/**
 *
 * @return 0表示成功
 * 1表示用户名重复
 * 2表示失败
 */
public int reg(String name, String password){
    User loadUserByUsername = userMapper.loadUserByUsername(name);
    if (loadUserByUsername != null) {
        return 1;
    }
    //插入用户,插入之前先对密码进行加密
    User user=new User();
    user.setUsername(name);
    user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
    user.setEnabled(true);//用户可用
    long result = userMapper.reg(user);
    boolean b =result == 1;
    if (b) {
        return 0;
    } else {
        return 2;
    }

}


    /**
     *
     * @return 0表示成功
     * 1表示用户名不存在
     * 2表示用户被锁
     * 3表示失败
     */
    public int login(String name, String password) {
        User loadUserByUsername = userMapper.loadUserByUsername(name);
        if (loadUserByUsername == null) {
            return 1;
        }
        if (!loadUserByUsername.isEnabled()) {
            return 2;
        }
       System.out.print("密码1"+loadUserByUsername.getPassword());
        System.out.print("密码2"+DigestUtils.md5DigestAsHex(password.getBytes()));
        boolean result=DigestUtils.md5DigestAsHex(password.getBytes()).equals(loadUserByUsername.getPassword());
        if(result){
          return 0;
        }else
          return 3;
    }



    /**
     *
     * @return
     * 1表示修改成功
     * 2表示失败
     */
    public int editPassword(String name,String newPassword) {

        newPassword=DigestUtils.md5DigestAsHex(newPassword.getBytes());
        long result=userMapper.editPassword(name,newPassword);
        boolean b=result==1;
        if(b){
            return 1;
        }else
            return 2;

    }

    public User GetPersonalInformation(String username){
        User loadUserByUsername = userMapper.loadUserByUsername(username);
        return loadUserByUsername;
    }



}
